<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
.header {
	background: #D8DFEA none repeat scroll 0%;
	border-top: 1px solid #3b5998;
	margin: 0px;
	padding: 2px 8px;
}

.tag_cloud {
	padding: 3px;
	text-decoration: none;
}

.tag_cloud:link {
	color: #3B5998;
}

.tag_cloud:visited {
	color: #3B5998;
}

.tag_cloud:hover {
	color: #ffffff;
	background: #3B5998;
}

.tag_cloud:active {
	color: #ffffff;
	background: #3B5998;
}
</style>

<!-- <title>iHacky</title> -->
</head>

<?php
/**
 * File: index.php
 *
 * This is the iHacky homepage file.  This file uses facebook mock ajax where
 * repeated calls for the search function are sent to.  Notice we included a
 * new PHP file called "mockajaxfbconfig.php".  This file is exactly the same
 * as the facebook API fbconfig.php file except for the "requireframe()" function
 * which has known issues with mock ajax. Notice the normal fbconfig.php file
 * is included after the mock ajax calls you see listed below.
 *
 * @version 1.0
 * @project iHacky
 */
/**
 * 
 */
include 'lib/mockajaxfbconfig.php';
include 'lib/config.php';
include 'iHackyFunctions.php';

// following if statement retrieves the FORM from the mock ajax call
// to add the user's hackystat info.
if(isset($_REQUEST['hackystat_id']) && isset($_REQUEST['hackystat_password'])){

	$conn = getDbConn(); //gets DB connection

	$hackystat_id = $_REQUEST['hackystat_id'];
	$hackystat_password = $_REQUEST['hackystat_password'];

	//mysql_real_escape_string is a mysql built in function to prevent sql injections
	$hackystat_id = mysql_real_escape_string($hackystat_id);
	$hackystat_password = mysql_real_escape_string($hackystat_password);

	//hackystat Coupling data URI, used for testing login
	$hackystatCouplingURL = "http://dasha.ics.hawaii.edu:9876/sensorbase/".
                        "sensordata/".$hackystat_id."?sdt=Coupling";
	$facebook_id = $user;

	if(testLogin($hackystatCouplingURL, $hackystat_id, $hackystat_password)) {

		// SQL query to inserts new account to the database.
		$query = "INSERT INTO USERS (facebook_id, hackystat_id, hackystat_password)" .
                 "VALUES ('$facebook_id', '$hackystat_id', AES_ENCRYPT('$hackystat_password','414'))";

			
		// invoke the SQL query, prints error if errors out.
		mysql_query($query, $conn) or DIE(mysql_error());

		echo "<br><b><font color=\"#666666\">Submission Successful!</font></b>
              <img src=\"http://www.ikoaguild.com/ihacky/images/check.png\"<br>";
		closeDb($conn);
	}
	else {
		echo "<div align=center><b><font color=\"#FF0000\">Username or Password<br>not valid!
                 </font></b><br>
                 <img src=\"http://www.ikoaguild.com/ihacky/images/problemIcon.png\"> 
                 <br>Click here to <a href=\"index.php\">Retry</a></div><br>";
	}
	exit;
}

//following if statement to recieve FORM data from mock ajax calls.
if(isset($_REQUEST['userInput'])){


	$expertiseKeyword = $_REQUEST['userInput'];
	$ranktest = $_REQUEST['rank'];
	$conn = getDbConn();

	//mysql built in function to prevent sql injections
	$expertiseKeyword = mysql_real_escape_string($expertiseKeyword);

	$pageNum = 1;   //sets first page to 1
	$rowsPerPage = 25;  //sets the maximum number of elements per page

	//accepts the new page number form the FORM
	if(isset($_REQUEST['page'])){
		$pageNum = $_REQUEST['page'];
	}

	$offset = ($pageNum - 1) * $rowsPerPage;

	//query to retrieve the count of rows for the search
	$qryGetSearchExpertiseResultsCount = "SELECT class_detail FROM CLASS
	WHERE MATCH (class_name,class_detail) AGAINST ('\"$expertiseKeyword\"' IN BOOLEAN MODE)";

	$rowCount = mysql_query($qryGetSearchExpertiseResultsCount, $conn)
	or DIE(mysql_error()."Error: qryGetSearchExpertiseResultsCount");
	$numRows = mysql_num_rows($rowCount);
	$maxPage = ceil($numRows/$rowsPerPage);


	//query to retrieve actual data to be displayed on page
	$qryGetSearchExpertiseResults = "SELECT class_detail FROM CLASS
	WHERE MATCH (class_name,class_detail) AGAINST ('\"$expertiseKeyword\"' IN BOOLEAN MODE)
	LIMIT $offset, $rowsPerPage";

	$result = mysql_query($qryGetSearchExpertiseResults, $conn)
	or DIE(mysql_error()."Error: qryGetSearchExpertiseResults");

	//test to see if last page is displayed, then find the number of the last element
	if($pageNum == $maxPage){
		$lastItem = $offset + ($numRows - (($pageNum - 1) * $rowsPerPage));
	}
	else {
		$lastItem = ($offset + $rowsPerPage);
	}

	$offset++;

	if (mysql_num_rows($result) > 0) {
		$counter = 1;

		//prints the loader icon DIV section
		echo '<div align="center">
              <img src="http://www.ikoaguild.com/ihacky/images/ajax-loader.gif" id="loadIcon"
              style="display: none;"/>
             </div>';

		//prints the FBML tag to create a header
		echo "<fb:header icon=\"false\" decoration=\"add_border\">
                Search returned total of ".$numRows." result(s)...
              </fb:header><br>";

		//prints the banner to display the number section of the results
		echo "<div class=\"header\">";
		echo  "<div align=\"left\">
		<b><font color=\"#3B5998\">
		Displaying results: $offset - $lastItem<br>
		</font></b>
		</div>";
		echo "</div>";
		echo "<div align=\"center\">
		<b><font color=\"#666666\">
		Page $pageNum of $maxPage
		</font></b><br>
		</div>";

		//while loop to display all results from the query
		while($resultsArray = mysql_fetch_array($result)){

			$dependencyName = $resultsArray['class_detail'];

			echo "<form id=\"$counter\">
			<input name=\"userInputInfo\" type=\"hidden\" value=\"$dependencyName\">
			<input name=\"rank\" type=\"hidden\" value=\"$ranktest\">
			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"$counter\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			$dependencyName
			</a>
			</form>";
			$counter++;
		}

		//test to see if page number is 1 then print only the --next-- link
		if($pageNum == 1 && ($numRows > $rowsPerPage)){
			$newPageNum = $pageNum + 1;
			echo '<br><br>';

			echo "<div align=\"center\">
			<form id=\"first_page\">
			<input name=\"userInput\" type=\"hidden\" value=\"$expertiseKeyword\">
			<input name=\"page\" type=\"hidden\" value=\"$newPageNum\">
			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"first_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			Next
			<img src=\"http://www.ikoaguild.com/ihacky/images/forwardarrow.png\" align=\"top\">
			</a>
			</form>
			</div>";

		}
		//test to see if page is between first page and last page
		//if so then print a previous and next link
		else if($pageNum < $maxPage){
			echo '<br><br>';
			$previousPageNum = $pageNum - 1;
			echo "<div align=\"center\">
			<table>
			<tr>
			<td>

			<form id=\"pre_page\">
			<input name=\"userInput\" type=\"hidden\" value=\"$expertiseKeyword\">
			<input name=\"page\" type=\"hidden\" value=\"$previousPageNum\">

			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"pre_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			<img src=\"http://www.ikoaguild.com/ihacky/images/reversearrow.png\" align=\"top\">
			Previous
			</a>
			</form>

			</td>";
			$nextPageNum = $pageNum + 1;
			echo "<td>

			<form id=\"next_page\">
			<input name=\"userInput\" type=\"hidden\" value=\"$expertiseKeyword\">
			<input name=\"page\" type=\"hidden\" value=\"$nextPageNum\">
			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"next_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			Next
			<img src=\"http://www.ikoaguild.com/ihacky/images/forwardarrow.png\" align=\"top\">
			</a>
			</form>

			</td>
			</tr>
			</table>
			</div>";
		}
		//test to see if page is last page, then print only previous link
		else if($pageNum == $maxPage && ($numRows > $rowsPerPage)){
			echo '<br><br>';
			$newPageNum = $pageNum - 1;
			echo "<div align=\"center\">
			<form id=\"last_page\">
			<input name=\"userInput\" type=\"hidden\" value=\"$expertiseKeyword\">
			<input name=\"page\" type=\"hidden\" value=\"$newPageNum\">

			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"last_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			<img src=\"http://www.ikoaguild.com/ihacky/images/reversearrow.png\" align=\"top\">
			Previous
			</a>
			</form>
			</div>";
		}
			
	}
	else{
		echo '
              <div align="center">
                <img src="http://www.ikoaguild.com/ihacky/images/ajax-loader.gif" id="loadIcon"
                 style="display: none;"/>
              </div>';   

		echo "<fb:header icon=\"false\" decoration=\"add_border\">
           Search returned 0 results...</fb:header><br>";

	}
	closeDb($conn);
	exit;
}

//following if statment to recieve FORM data from the mock ajax calls
if(isset($_REQUEST['userInputInfo'])){

	$conn = getDbConn(); //get db connection
	$pageNum = 1;
	$rowsPerPage = 10;

	//test if page number has changed from previous calls
	if(isset($_REQUEST['memberPages'])){
		$pageNum = $_REQUEST['memberPages'];
	}

	$offset = ($pageNum - 1) * $rowsPerPage;

	$keyword = $_REQUEST['userInputInfo'];

	//mysql built in function to prevent sql injections
	$keyword = mysql_real_escape_string($keyword);

	$rank = $_REQUEST['rank'];

	//query to retrieve the number of rows of the search
	$qryGetSearchResultsCount = "SELECT CLASS.class_detail,
	CLASS_USERS.facebook_id, CLASS_USERS.time_start,
	CLASS_USERS.time_last, CLASS_USERS.time_used,
	CLASS_USERS.class_rank FROM CLASS, CLASS_USERS
	WHERE CLASS.class_id = CLASS_USERS.class_id
	AND CLASS_USERS.facebook_id != $user
	AND CLASS_USERS.class_rank != 0
	AND MATCH (class_name,class_detail) AGAINST ('\"$keyword\"' IN BOOLEAN MODE)
	ORDER BY FIELD(CLASS_USERS.class_rank, '$rank') DESC;";

	$rowCount = mysql_query($qryGetSearchResultsCount, $conn) or DIE(mysql_error()."test 1");
	$numRows = mysql_num_rows($rowCount);
	$maxPage = ceil($numRows/$rowsPerPage);

	//query to display actual data to the page
	$qryGetSearchResults = "SELECT CLASS.class_detail,
	CLASS_USERS.facebook_id, CLASS_USERS.time_start,
	CLASS_USERS.time_last, CLASS_USERS.time_used,
	CLASS_USERS.class_rank FROM CLASS, CLASS_USERS
	WHERE CLASS.class_id = CLASS_USERS.class_id
	AND CLASS_USERS.facebook_id != $user
	AND CLASS_USERS.class_rank != 0
	AND MATCH (class_name,class_detail) AGAINST ('\"$keyword\"' IN BOOLEAN MODE)
	ORDER BY FIELD(CLASS_USERS.class_rank, '$rank') DESC
	LIMIT $offset, $rowsPerPage;";

	$results = mysql_query($qryGetSearchResults, $conn) or DIE(mysql_error()."test2");

	//test to see if page is the last page, to determine the last elements number
	if($pageNum == $maxPage){
		$lastItem = $offset + ($numRows - (($pageNum - 1) * $rowsPerPage));
	}
	else{
		$lastItem = ($offset + $rowsPerPage);
	}
	$offset++;

	$counter = 1;

	if(mysql_num_rows($results) > 0){

		//prints the DIV section that contains the loader icon
		echo '<div align="center">
                 <img src="http://www.ikoaguild.com/ihacky/images/ajax-loader.gif" id="loadIcon"
                 style="display: none;"/>
              </div>';

		//fbml tag to render a facebook style header
		echo "<fb:header icon=\"false\" decoration=\"add_border\">
                   Search returned ".mysql_num_rows($results)." member(s)... 
               </fb:header>";
		echo '<br>';

		//prints the banner that displays the number index of the items
		echo "<div class=\"header\">";
		echo  "<div align=\"left\">
		<b><font color=\"#3B5998\">
		Displaying results: $offset - $lastItem<br>
		</font></b>
		</div>";
		echo "</div>";
		echo "<div align=\"center\">
		<b><font color=\"#666666\">
		Page $pageNum of $maxPage
		</font></b><br>
		</div>";

		echo "<table border=\"0\" width=\"100%\">
                 <tr>
                   <th bgcolor=\"#EEEEEE\">
                     Member Name 
                   </th>
                   <th bgcolor=\"#EEEEEE\">
                     Class Name 
                   </th>
                   <th bgcolor=\"#EEEEEE\">
                     Date Last Used 
                   </th>
                   <th bgcolor=\"#EEEEEE\">
                     Proficiency 
                   </th>
                  <tr>";

		//create a variable to toggle the background color for each row
		$colorFlag = false;
		
		//while loop to display information on the page
		while($resultsArray = mysql_fetch_array($results)){

			if($colorFlag){
				$color = "#FFEEFF";
			}
			else{
				$color = "#FFFFFF";
			}
			$currentID = $resultsArray['facebook_id'];

			echo "<tr bgcolor=\"$color\">";
			echo   "<td>";
			echo    "<fb:name firstnameonly=\"true\" uid=\"$currentID\"/><br>";
			echo "<a onclick=\"showdiv('$counter');\">Ask this expert for help!</a>
			<div id=\"$counter\" style=\"display: none\">";

			$counter++;
			$sender = $user;
			$recipient = $resultsArray['facebook_id'];
			$messageSubject = "Please help.";
			$messageBody = "Hi";
			$messageHandler = "store_message.php";
			$createMessage = new Message($sender, $recipient, $messageSubject, $messageBody, "Time",
                                         "0", $messageHandler);
			$result = $createMessage->createMessageForm();

			echo "<a onclick=\"showdiv('$counter');\">View User's Profile</a>
			<div id=\"$counter\" style=\"display: none\">";
			showClasses($resultsArray['facebook_id'], false);
			echo "</div>
                 </div>";

			echo   "</td>";
			echo   "<td>";
			echo     $resultsArray['class_detail'];
			echo   "</td>";
			echo   "<td>";
			echo      $resultsArray['time_last'];
			echo    "</td>";
			echo    "<td>";
			echo      $resultsArray['class_rank'];
			echo    "</td>";
			echo "</tr>";

			$colorFlag = !$colorFlag; //toggle the variable
			$counter++;
		}
		echo "</table>";

		//check if page is the first page, print only next link
		if($pageNum == 1 && ($numRows > $rowsPerPage)){
			$newPageNum = $pageNum + 1;
			echo '<br><br>';

			echo "<div align=\"center\">
			<form id=\"first_page\">
			<input name=\"userInputInfo\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$newPageNum\">
			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"first_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			Next
			<img src=\"http://www.ikoaguild.com/ihacky/images/forwardarrow.png\" align=\"top\">
			</a>
			</form>
			</div>";

		}
		//check to see if page is between first and last, then print previous and next links
		else if($pageNum < $maxPage){
			echo '<br><br>';
			$previousPageNum = $pageNum - 1;
			echo "<div align=\"center\">
			<table>
			<tr>
			<td>

			<form id=\"pre_page\">
			<input name=\"userInputInfo\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$previousPageNum\">

			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"pre_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			<img src=\"http://www.ikoaguild.com/ihacky/images/reversearrow.png\" align=\"top\">
			Previous
			</a>
			</form>

			</td>";
			$nextPageNum = $pageNum + 1;
			echo "<td>

			<form id=\"next_page\">
			<input name=\"userInputInfo\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$nextPageNum\">
			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"next_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			Next
			<img src=\"http://www.ikoaguild.com/ihacky/images/forwardarrow.png\" align=\"top\">
			</a>
			</form>

			</td>
			</tr>
			</table>
			</div>";
		}
		//check to see if page is last page, then print only previous link
		else if($pageNum == $maxPage && ($numRows > $rowsPerPage)){
			echo '<br><br>';
			$newPageNum = $pageNum - 1;
			echo "<div align=\"center\">
			<form id=\"last_page\">
			<input name=\"userInputInfo\" type=\"hidden\" value=\"$keyword\">
			<input name=\"memberPages\" type=\"hidden\" value=\"$newPageNum\">

			<a clickrewriteurl=\"http://www.ikoaguild.com/ihacky/\"
			clickrewriteform=\"last_page\"
			clickrewriteid=\"content\"
			clicktoshow=\"loadIcon\">
			<img src=\"http://www.ikoaguild.com/ihacky/images/reversearrow.png\" align=\"top\">
			Previous
			</a>
			</form>
			</div>";
		}
	}
	else{
		echo '<div align="center">
                <img src="http://www.ikoaguild.com/ihacky/images/ajax-loader.gif" id="loadIcon"
                 style="display: none;"/>
              </div>';   

		echo "<fb:header icon=\"false\" decoration=\"add_border\">
           Search returned 0 member(s)...</fb:header><br>";

	}
	closeDb($conn);  //close db connection
	exit;
}

//prints the java script to allow the collapsing effect
printJavaScriptDiv();

//prints the FBML tag to render the page's title
printTitle();

//prints the dashboard of the page
printDashboard();

include 'lib/fbconfig.php';

//prints the banner of the page
printBanner($user);

//prints the FBML tags to render navigation tabs
printFbmlTabs(1);
echo "<br>";

//prints the search FORM on the page
printSearchTable();
echo "<br><br>";

//prints the expertise tag cloud
showExpertiseTagCloud();
$count = getNumUserClasses($user);

//contains the html code to be displayed on the user's profile
// ihacky section. The html code renders another search box
// in the user's profile ihacky section
$fbml = <<<ProfileSearchBox

<fb:subtitle seeallurl="http://apps.facebook.com/ihackyapp/" >
<fb:action href="messagebox.php">
Message Box
</fb:action>
<fb:name firstnameonly="true" uid="$user" useyou="false" linked="false"/>
knows $count different classes.
</fb:subtitle>

<span style="display:none"><fb:editor></fb:editor></span>
<form id="search_form">
<table class="editorkit" border="0" cellspacing="0" style="width:400px">
<tr class="width_setter">
 <th style="width:50px"></th>
 <td></td>
</tr>
<tr>
<th class="detached_label">
<label>Expertise Search:</label>
</th>
<td class="editorkit_row">
<input type="text" name="userInput"/> 
</td>
<th class="detached_label">
<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Rank:</label>
</th> 
<td class="editorkit_row"> 
   <select name="rank">  
   <option value="1">1</option>  
   <option value="2">2</option>  
   <option value="3">3</option>
   <option value="4">4</option>
   <option value="5">5</option>  
   </select>  
 
</td>
<td class="right_padding">
</td>
</tr>
<tr>
<th>
</th>
<td class="editorkit_buttonset">
 <input type="submit" class="editorkit_button action" value="Search"  
              clickrewriteurl="http://www.ikoaguild.com/ihacky/ihackyProfileSection.php"
              clickrewriteform="search_form" 
              clickrewriteid="content"
              clicktoshow="loadIcon"/>
</td>
<td class="right_padding"></td></tr>
</table>
</form>
<div id="content">
   <div align="center">
     <img src="http://www.ikoaguild.com/ihacky/images/ajax-loader.gif" id="loadIcon"
        style="display:none;" />  
   </div>
</div>


ProfileSearchBox;

//facebook API method to display html code onto the user's profile section
$facebook->api_client->profile_setFBML($fbml, $user);
?>